﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyTruongHoc_App.MyDataSet;
using QuanLyTruongHoc_App.MyDataSet.QLTHTableAdapters;

namespace QuanLyTruongHoc_App
{
    public partial class SoDiem : Form
    {
        private DataTable data, dataCaNam;
        private List<int> lIdDiem;
        private List<float> lHSDiem;
        private int state, 
                    unEditCol,
                    idNamHoc,
                    idMonHoc, 
                    idHocKy;

        private Boolean wasSave;

        public SoDiem()
        {
            InitializeComponent();
            lIdDiem = new List<int>();
            lHSDiem = new List<float>();
            dg_DanhSach.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dg_DanhSach_DataBindingComplete);
        }

        private void QuanLyGiaoVien_Load(object sender, EventArgs e)
        {
            refreshData();
            wasSave = true;
        }

        private void checkUserPower()
        {
            int pow = PublicLib.getUserPower(PConst.QUYEN_QL_SO_DIEM);
            // user co quyen view
            tscb_NamHoc.Enabled = ((pow & PConst.POW_VIEW) > 0);
            // user co quyen them
            //tsb_TaoMoi.Enabled = ((pow & PConst.POW_ADD) > 0);
            // user co quyen edit
            tsb_Edit.Enabled = 
                tsb_Luu.Enabled = ((pow & PConst.POW_EDIT) > 0);
            for (int i = unEditCol; i < dg_DanhSach.ColumnCount - 2; i++)
                dg_DanhSach.Columns[i].ReadOnly = !tsb_Edit.Enabled;
            dg_DanhSach.Columns[dg_DanhSach.ColumnCount - 1].ReadOnly = !tsb_Edit.Enabled;
            // user co delete
            //tsb_Delete.Enabled = ((pow & PConst.POW_DEL) > 0);
        }

        private void loadComboMonHoc()
        {
            if (tscb_Lop.SelectedIndex == -1)
                return;
            int idLop = (int)qLTH.tbl_LopHoc[tscb_Lop.SelectedIndex][qLTH.tbl_LopHoc.idColumn];
            // Mon Hoc
            MyDataSet.QLTHTableAdapters.tbl_MonHocTableAdapter monAdap = new tbl_MonHocTableAdapter();
            monAdap.Connection.ConnectionString = PublicLib.getStrConn();
            monAdap.FillByLopHoc(qLTH.tbl_MonHoc, idLop);

            tscb_MonHoc.Items.Clear();
            for (int i = 0; i < qLTH.tbl_MonHoc.Rows.Count; i++)
            {
                tscb_MonHoc.Items.Add(qLTH.tbl_MonHoc.Rows[i][qLTH.tbl_MonHoc.TenMonHocColumn].ToString());
            }
            if (tscb_MonHoc.Items.Count > 0)
                tscb_MonHoc.SelectedIndex = 0;
            // --------------
        }

        private void reloadComboBox()
        {
            state = PConst.STATE_LOAD;
            // Lop
            MyDataSet.QLTHTableAdapters.tbl_LopHocTableAdapter lopAdap = new tbl_LopHocTableAdapter();
            lopAdap.Connection.ConnectionString = PublicLib.getStrConn();
            lopAdap.Fill(qLTH.tbl_LopHoc);

            tscb_Lop.Items.Clear();
            for (int i = 0; i < qLTH.tbl_LopHoc.Rows.Count; i++)
            {
                tscb_Lop.Items.Add(qLTH.tbl_LopHoc.Rows[i][qLTH.tbl_LopHoc.TenLopColumn].ToString());
            }
            tscb_Lop.SelectedIndex = 0;
            //tscb_Lop.Items.Add(MSG.MNU_ALL);
            // --------------
            loadComboMonHoc();
            // Nam Hoc
            MyDataSet.QLTHTableAdapters.tbl_NamHocTableAdapter namAdap = new tbl_NamHocTableAdapter();
            namAdap.Connection.ConnectionString = PublicLib.getStrConn();
            namAdap.FillByFlag(qLTH.tbl_NamHoc, PConst.FLAG_NONE);

            tscb_NamHoc.Items.Clear();
            for (int i = 0; i < qLTH.tbl_NamHoc.Rows.Count; i++)
            {
                tscb_NamHoc.Items.Add(qLTH.tbl_NamHoc.Rows[i][qLTH.tbl_NamHoc.TenColumn].ToString());
            }

            if (tscb_NamHoc.Items.Count > 0)
                tscb_NamHoc.SelectedIndex = tscb_NamHoc.Items.Count - 1;
            // --------------
            state = PConst.STATE_LOADED;
        }

        private void reloadDataTable()
        {
            data = new DataTable();
            // Add Ten Hoc Sinh column
            data.Columns.Add(qLTH.tbl_HocSinh.idColumn.ColumnName, Type.GetType("System.Int32"));
            data.Columns.Add(qLTH.tbl_HocSinh.HoDemColumn.ColumnName, Type.GetType("System.String"));
            data.Columns.Add(qLTH.tbl_HocSinh.TenColumn.ColumnName, Type.GetType("System.String"));
            data.Columns.Add(qLTH.tbl_HocSinh.GioiTinhColumn.ColumnName, Type.GetType("System.String"));
            data.Columns.Add(qLTH.tbl_HocSinh.NgaySinhColumn.ColumnName, Type.GetType("System.DateTime"));
            // ---------
            // Add Loai Diem
            MyDataSet.QLTHTableAdapters.tbl_LoaiDiemTableAdapter diemAdap = new tbl_LoaiDiemTableAdapter();
            diemAdap.Connection.ConnectionString = PublicLib.getStrConn();
            diemAdap.ClearBeforeFill = true;
            diemAdap.FillByFlag(qLTH.tbl_LoaiDiem, PConst.FLAG_NONE);

            String diemHK = PublicLib.getOptionValue(QLLoaiDiem.OPT_DIEM_HK);
            lIdDiem.Clear();
            lHSDiem.Clear();
            int li = -1;
            for (int i = 0; i < qLTH.tbl_LoaiDiem.Rows.Count; i++)
                if (!(qLTH.tbl_LoaiDiem.Rows[i][qLTH.tbl_LoaiDiem.idColumn].ToString() == diemHK))
                {
                    data.Columns.Add(qLTH.tbl_LoaiDiem.Rows[i][qLTH.tbl_LoaiDiem.LoaiDiemColumn].ToString() + " (x" +
                                     qLTH.tbl_LoaiDiem.Rows[i][qLTH.tbl_LoaiDiem.HeSoColumn].ToString() + ")",
                                     Type.GetType("System.String"));
                    lIdDiem.Add(int.Parse(qLTH.tbl_LoaiDiem.Rows[i][qLTH.tbl_LoaiDiem.idColumn].ToString()));
                    lHSDiem.Add(float.Parse(qLTH.tbl_LoaiDiem.Rows[i][qLTH.tbl_LoaiDiem.HeSoColumn].ToString()));
                }
                else
                    li = i; // luu diem hk
            // Diem HK
            if (li != -1)
            {
                data.Columns.Add(qLTH.tbl_LoaiDiem.Rows[li][qLTH.tbl_LoaiDiem.LoaiDiemColumn].ToString(),
                                 Type.GetType("System.String"));

                lIdDiem.Add(int.Parse(qLTH.tbl_LoaiDiem.Rows[li][qLTH.tbl_LoaiDiem.idColumn].ToString()));
                lHSDiem.Add(float.Parse(qLTH.tbl_LoaiDiem.Rows[li][qLTH.tbl_LoaiDiem.HeSoColumn].ToString()));
            }
            // Diem TB ca Ky
            data.Columns.Add(MSG.MNU_TB_CA_KY, Type.GetType("System.Single"));
            // Thi Lai
            data.Columns.Add(MSG.MNU_THI_LAI, Type.GetType("System.Boolean"));
            // ---------
            // data ca nam
            dataCaNam = new DataTable();
            // Add Ten Hoc Sinh column
            dataCaNam.Columns.Add(qLTH.tbl_HocSinh.idColumn.ColumnName, Type.GetType("System.Int32"));
            dataCaNam.Columns.Add(qLTH.tbl_HocSinh.HoDemColumn.ColumnName, Type.GetType("System.String"));
            dataCaNam.Columns.Add(qLTH.tbl_HocSinh.TenColumn.ColumnName, Type.GetType("System.String"));
            dataCaNam.Columns.Add(qLTH.tbl_HocSinh.GioiTinhColumn.ColumnName, Type.GetType("System.String"));
            dataCaNam.Columns.Add(qLTH.tbl_HocSinh.NgaySinhColumn.ColumnName, Type.GetType("System.DateTime"));

            dataCaNam.Columns.Add("HK I", Type.GetType("System.Single"));
            dataCaNam.Columns.Add("HK II", Type.GetType("System.Single"));
            dataCaNam.Columns.Add("Cả Năm", Type.GetType("System.Single"));
            // --------------------
            fillData();
        }

        private void loadDataKy()
        {
            // set data source
            dg_DanhSach.DataSource = null;
            dg_DanhSach.Columns.Clear();
            dg_DanhSach.Columns.Add("grc_stt", "STT");

            dg_DanhSach.DataSource = data;
            dg_DanhSach.Columns[0].Width = 40;

            dg_DanhSach.Columns[1].Visible = false; //id
            dg_DanhSach.Columns[2].HeaderText = "Họ Đệm";
            dg_DanhSach.Columns[3].HeaderText = "Tên";
            dg_DanhSach.Columns[3].Width = 60;
            dg_DanhSach.Columns[4].HeaderText = "Giới Tính";
            dg_DanhSach.Columns[4].Width = 60;
            dg_DanhSach.Columns[5].HeaderText = "Ngày Sinh";
            dg_DanhSach.Columns[5].DefaultCellStyle.Format = "dd/MM/yyyy";

            unEditCol = 6;
            for (int i = 0; i < unEditCol; i++)
                dg_DanhSach.Columns[i].ReadOnly = true;

            //dg_DanhSach.Columns[dg_DanhSach.ColumnCount - 2].ReadOnly = true;

            for (int i = unEditCol; i < dg_DanhSach.ColumnCount; i++)
                dg_DanhSach.Columns[i].Width = 60;

            dg_DanhSach.Columns[dg_DanhSach.ColumnCount - 2].ReadOnly = true;
            // end set data source
            idNamHoc = (int)(qLTH.tbl_NamHoc.Rows[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn]);
            idMonHoc = (int)(qLTH.tbl_MonHoc.Rows[tscb_MonHoc.SelectedIndex][qLTH.tbl_MonHoc.idColumn]);
            idHocKy = (int)qLTH.tbl_HocKy[tscb_HocKy.SelectedIndex][qLTH.tbl_HocKy.idColumn];

            int idLop = int.Parse(qLTH.tbl_LopHoc.Rows[tscb_Lop.SelectedIndex][qLTH.tbl_LopHoc.idColumn].ToString());

            MyDataSet.QLTHTableAdapters.tbl_HocSinhTableAdapter hsAdap = new tbl_HocSinhTableAdapter();
            hsAdap.Connection.ConnectionString = PublicLib.getStrConn();
            hsAdap.ClearBeforeFill = true;
            //hsAdap.FillByLopCu(qLTH.tbl_HocSinh, idNamHoc, idLop, PConst.FLAG_NONE);
            if (tscb_NamHoc.SelectedIndex == tscb_NamHoc.Items.Count - 1)
                hsAdap.FillByLopCu(qLTH.tbl_HocSinh, idNamHoc, idLop, PConst.FLAG_NONE);
            else
                hsAdap.FillByLopCuAll(qLTH.tbl_HocSinh, idNamHoc, idLop);

            data.Rows.Clear();
            MyDataSet.QLTHTableAdapters.qh_DiemTableAdapter diemAdp = new qh_DiemTableAdapter();
            diemAdp.Connection.ConnectionString = PublicLib.getStrConn();
            diemAdp.ClearBeforeFill = true;

            qh_HocSinhMonHocTableAdapter hsMonHoc = new qh_HocSinhMonHocTableAdapter();
            hsMonHoc.Connection.ConnectionString = PublicLib.getStrConn();
            hsMonHoc.ClearBeforeFill = true;
            hsMonHoc.FillByHocKyMonHoc(qLTH.qh_HocSinhMonHoc, idMonHoc, idHocKy);

            for (int i = 0; i < qLTH.tbl_HocSinh.Rows.Count; i++)
            {
                DataRow nRow = data.NewRow();
                int idHS = (int)qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.idColumn];
                nRow[0] = idHS; // id
                nRow[1] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.HoDemColumn]; // Ho Dem
                nRow[2] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.TenColumn]; // Ten
                int gt = (int)qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.GioiTinhColumn]; // Ho Dem
                nRow[3] = (gt == 0 ? "Nam" : "Nữ");
                nRow[4] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.NgaySinhColumn];
                diemAdp.FillByHocSinhMonHocNamHoc(qLTH.qh_Diem, idHS, idMonHoc, idHocKy);

                for (int j = unEditCol - 1; j < data.Columns.Count - 2; j++)
                {
                    DataRow[] tmpRow = qLTH.qh_Diem.Select(qLTH.qh_Diem.idDiemColumn.ColumnName + "=" + lIdDiem[j - unEditCol + 1]);
                    if (tmpRow.Length > 0)
                        nRow[j] = tmpRow[0][qLTH.qh_Diem.DiemColumn];
                }

                DataRow[] tRow = qLTH.qh_HocSinhMonHoc.Select(qLTH.qh_HocSinhMonHoc.idHocSinhColumn + "=" + idHS);
                if (tRow.Length > 0)
                    nRow[MSG.MNU_THI_LAI] = tRow[0][qLTH.qh_HocSinhMonHoc.ThiLaiColumn];
                else
                    nRow[MSG.MNU_THI_LAI] = false;
                data.Rows.Add(nRow);
            }

            dg_DanhSach.Sort(dg_DanhSach.Columns[3], ListSortDirection.Ascending); // ten
            dg_DanhSach.Columns[3].HeaderCell.SortGlyphDirection = SortOrder.Ascending;

            calculateData();
        }

        private void loadDataCaNam()
        {
            // set data source
            dg_DanhSach.DataSource = null;
            dg_DanhSach.Columns.Clear();
            dg_DanhSach.Columns.Add("grc_stt", "STT");

            dg_DanhSach.DataSource = dataCaNam;
            dg_DanhSach.Columns[0].Width = 40;

            dg_DanhSach.Columns[1].Visible = false; //id
            dg_DanhSach.Columns[2].HeaderText = "Họ Đệm";
            dg_DanhSach.Columns[3].HeaderText = "Tên";
            dg_DanhSach.Columns[3].Width = 60;
            dg_DanhSach.Columns[4].HeaderText = "Giới Tính";
            dg_DanhSach.Columns[4].Width = 70;
            dg_DanhSach.Columns[5].HeaderText = "Ngày Sinh";
            dg_DanhSach.Columns[5].DefaultCellStyle.Format = "dd/MM/yyyy";

            for (int i = 0; i < dg_DanhSach.ColumnCount; i++)
                dg_DanhSach.Columns[i].ReadOnly = true;
            // -------------------------------
            idNamHoc = (int)(qLTH.tbl_NamHoc.Rows[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn]);
            idMonHoc = (int)(qLTH.tbl_MonHoc.Rows[tscb_MonHoc.SelectedIndex][qLTH.tbl_MonHoc.idColumn]);
            //idHocKy = (int)qLTH.tbl_HocKy[tscb_HocKy.SelectedIndex][qLTH.tbl_HocKy.idColumn];
            int idLop = int.Parse(qLTH.tbl_LopHoc.Rows[tscb_Lop.SelectedIndex][qLTH.tbl_LopHoc.idColumn].ToString());

            tbl_HocSinhTableAdapter hsAdap = new tbl_HocSinhTableAdapter();
            hsAdap.Connection.ConnectionString = PublicLib.getStrConn();
            hsAdap.ClearBeforeFill = true;
            if (tscb_NamHoc.SelectedIndex == tscb_NamHoc.Items.Count - 1) 
                hsAdap.FillByLopCu(qLTH.tbl_HocSinh, idNamHoc, idLop, PConst.FLAG_NONE);
            else
                hsAdap.FillByLopCuAll(qLTH.tbl_HocSinh, idNamHoc, idLop);
            

            dataCaNam.Rows.Clear();
            qh_HocSinhMonHocTableAdapter diemAdp = new qh_HocSinhMonHocTableAdapter();
            diemAdp.Connection.ConnectionString = PublicLib.getStrConn();
            diemAdp.ClearBeforeFill = true;

            MyDataSet.QLTH.qh_HocSinhMonHocDataTable hk1 = new MyDataSet.QLTH.qh_HocSinhMonHocDataTable(),
                                                     hk2 = new MyDataSet.QLTH.qh_HocSinhMonHocDataTable();

            diemAdp.FillByHocKyMonHoc(hk1, idMonHoc, (int)qLTH.tbl_HocKy[0][qLTH.tbl_HocKy.idColumn]);
            diemAdp.FillByHocKyMonHoc(hk2, idMonHoc, (int)qLTH.tbl_HocKy[1][qLTH.tbl_HocKy.idColumn]);

            for (int i = 0; i < qLTH.tbl_HocSinh.Rows.Count; i++)
            {
                DataRow nRow = dataCaNam.NewRow();
                int idHS = (int)qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.idColumn];
                nRow[0] = idHS; // id
                nRow[1] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.HoDemColumn]; // Ho Dem
                nRow[2] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.TenColumn]; // Ten
                int gt = (int)qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.GioiTinhColumn]; // Ho Dem
                nRow[3] = (gt == 0 ? "Nam" : "Nữ");
                nRow[4] = qLTH.tbl_HocSinh.Rows[i][qLTH.tbl_HocSinh.NgaySinhColumn];

                float diemKy1 = -1, diemKy2 = -1;
                DataRow[] tmp = hk1.Select(qLTH.qh_HocSinhMonHoc.idHocSinhColumn.ColumnName + "=" + idHS);
                if (tmp.Length > 0)
                {
                    nRow[5] = tmp[0][qLTH.qh_HocSinhMonHoc.DiemTBColumn.ColumnName];
                    if (nRow[5] != DBNull.Value)
                        diemKy1 = (float)nRow[5];
                }

                tmp = hk2.Select(qLTH.qh_HocSinhMonHoc.idHocSinhColumn.ColumnName + "=" + idHS);
                if (tmp.Length > 0)
                {
                    nRow[6] = tmp[0][qLTH.qh_HocSinhMonHoc.DiemTBColumn.ColumnName];
                    if (nRow[6] != DBNull.Value)
                        diemKy2 = (float)nRow[6];
                }

                if (diemKy1 != -1 && diemKy2 != -1)
                {
                    float canam = ((diemKy1 + 2 * diemKy2) / 3);
                    nRow[7] = canam.ToString(PConst.LAM_TRON);
                }
                else
                {
                    nRow[7] = (diemKy1 != -1) ? diemKy1 : diemKy2;
                }
                dataCaNam.Rows.Add(nRow);
            }

            dg_DanhSach.Sort(dg_DanhSach.Columns[3], ListSortDirection.Ascending);
            dg_DanhSach.Columns[3].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
        }

        private void fillData()
        {
            if (state == PConst.STATE_LOAD)
                return;

            if (tscb_HocKy.SelectedIndex < tscb_HocKy.Items.Count - 1)
                loadDataKy();
            else
                loadDataCaNam();
            wasSave = true;
        }

        private void refreshData()
        {
            reloadData();
            reloadComboBox();
            reloadDataTable();
        }

        private void QuanLyGiaoVien_Resize(object sender, EventArgs e)
        {
            dg_DanhSach.Width = this.Width - 5;
            dg_DanhSach.Height = stt_Bottom.Top - dg_DanhSach.Top - 1;
        }

        private void dg_DanhSach_DataBindingComplete(object sender, EventArgs e)
        {
            reloadData();
        }

        private void reloadData()
        {
            for (int i = 0; i < dg_DanhSach.RowCount; i++)
            {
                dg_DanhSach.Rows[i].Cells[0].Value = (i + 1);
                dg_DanhSach.Rows[i].DefaultCellStyle.BackColor = (i % 2 == 1) ? PConst.COLOR_BACK_1 : PConst.COLOR_BACK_DEF;
            }
        }

        private void dg_DanhSach_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            tsb_Edit_Click(tsb_Edit, new EventArgs());
        }

        private void tsb_Edit_Click(object sender, EventArgs e)
        {
            if (dg_DanhSach.SelectedCells.Count == 0)
                return;
            //if (!dg_DanhSach.SelectedColumns[0].ReadOnly)
                dg_DanhSach.BeginEdit(true);
        }

        private void tsb_Delete_Click(object sender, EventArgs e)
        {
            if (dg_DanhSach.SelectedCells.Count == 0)
                return;
            if (!dg_DanhSach.SelectedCells[0].ReadOnly)
            {
                dg_DanhSach.SelectedCells[0].Value = "";
                wasSave = false;
            }
        }

        private void tscb_Lop_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (state == PConst.STATE_LOAD)
                return;
            if (!wasSave)
            {
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
                wasSave = true;
            }
            state = PConst.STATE_LOAD;
            loadComboMonHoc();
            state = PConst.STATE_LOADED;
            fillData();

            if (PConst.TEST) tsb_Generate_Click(tsb_Generate, new EventArgs());
        }

        private void dg_DanhSach_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (!(e.ColumnIndex == dg_DanhSach.ColumnCount - 1))
            {
                String txt = dg_DanhSach.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (!PublicLib.checkStr(txt))
                {
                    // String loi
                    MessageBox.Show(MSG.MSG_NHAP_DANG_DIEM);
                    dg_DanhSach.CancelEdit();
                }
                else
                {
                    calculateData();
                    wasSave = false;
                }
            }
            else
                wasSave = false;
        }

        private void saveData()
        {
            if (wasSave)
                return;
            MyDataSet.QLTHTableAdapters.qh_DiemTableAdapter diemAdp = new qh_DiemTableAdapter();
            diemAdp.Connection.ConnectionString = PublicLib.getStrConn();
            diemAdp.ClearBeforeFill = true;

            diemAdp.FillByNamHocMonHoc(qLTH.qh_Diem, idMonHoc, idHocKy);

            MyDataSet.QLTHTableAdapters.qh_HocSinhMonHocTableAdapter hsMHAdap = new qh_HocSinhMonHocTableAdapter();
            hsMHAdap.Connection.ConnectionString = PublicLib.getStrConn();

            hsMHAdap.FillByHocKyMonHoc(qLTH.qh_HocSinhMonHoc, idMonHoc, idHocKy);

            for (int i = 0; i < data.Rows.Count; i++)
            {
                int idHS = (int)data.Rows[i][0];

                for (int j = unEditCol - 1; j < data.Columns.Count - 2; j++)
                {
                    String txt = data.Rows[i][j].ToString().Trim();
                    DataRow[] tmpRow = qLTH.qh_Diem.Select(qLTH.qh_Diem.idHocSinhColumn + "=" + idHS + " AND " +
                                                           qLTH.qh_Diem.idDiemColumn + "=" + lIdDiem[j - unEditCol + 1]);

                    if (txt == "")
                    {
                        if (tmpRow.Length > 0)
                        {
                            tmpRow[0].Delete();
                            diemAdp.Update(tmpRow[0]);
                        }
                    }
                    else
                    {
                        if (tmpRow.Length > 0)
                        {
                            tmpRow[0][qLTH.qh_Diem.DiemColumn] = txt;
                            //diemAdp.Update(tmpRow[0]);
                        }
                        else
                        {
                            DataRow newRow = qLTH.qh_Diem.NewRow();
                            newRow[qLTH.qh_Diem.idMonHocColumn] = idMonHoc;
                            newRow[qLTH.qh_Diem.idHocSinhColumn] = idHS;
                            newRow[qLTH.qh_Diem.idNamHocColumn] = idHocKy;
                            newRow[qLTH.qh_Diem.idDiemColumn] = lIdDiem[j - unEditCol + 1];

                            newRow[qLTH.qh_Diem.DiemColumn] = txt;
                            qLTH.qh_Diem.Rows.Add(newRow);

                            //diemAdp.Update(newRow);
                        }
                    }
                }

                /* Diem TB */
                String txt1 = data.Rows[i][data.Columns.Count - 2].ToString().Trim();
                DataRow [] tmpRow1 = qLTH.qh_HocSinhMonHoc.Select(qLTH.qh_HocSinhMonHoc.idHocSinhColumn.ColumnName + "=" + idHS);
                Boolean thiLai = false;
                if (data.Rows[i][data.Columns.Count - 1] != DBNull.Value)
                    thiLai = (Boolean)data.Rows[i][data.Columns.Count - 1];

                if (txt1 == "") txt1 = "0";
                if (tmpRow1.Length > 0)
                {
                    tmpRow1[0][qLTH.qh_HocSinhMonHoc.DiemTBColumn] = txt1;
                    tmpRow1[0][qLTH.qh_HocSinhMonHoc.ThiLaiColumn] = thiLai;
                    //hsMHAdap.Update(tmpRow1[0]);
                }
                else
                {
                    DataRow newRow1 = qLTH.qh_HocSinhMonHoc.NewRow();
                    newRow1[qLTH.qh_HocSinhMonHoc.idMonHocColumn] = idMonHoc;
                    newRow1[qLTH.qh_HocSinhMonHoc.idHocSinhColumn] = idHS;
                    newRow1[qLTH.qh_HocSinhMonHoc.idNamHocColumn] = idHocKy;
                    newRow1[qLTH.qh_HocSinhMonHoc.ThiLaiColumn] = thiLai;
                            
                    newRow1[qLTH.qh_HocSinhMonHoc.DiemTBColumn] = txt1;
                    qLTH.qh_HocSinhMonHoc.Rows.Add(newRow1);

                    //hsMHAdap.Update(newRow1);
                }
            }

            diemAdp.Update(qLTH.qh_Diem);
            hsMHAdap.Update(qLTH.qh_HocSinhMonHoc);
            wasSave = true;
        }

        private void tsb_Luu_Click(object sender, EventArgs e)
        {
            dg_DanhSach.EndEdit();
            saveData();
        }

        private void SoDiem_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!wasSave) 
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
        }

        private void dg_DanhSach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                tsb_Delete_Click(tsb_Delete, new EventArgs());
            }
        }

        private void calculateData()
        {
            for (int i = 0; i < data.Rows.Count; i++)
            {
                float result = 0;
                float dv = 0;
                int j;
                for (j = unEditCol - 1; j < data.Columns.Count - 3; j++)
                {
                    List<float> tmp = PublicLib.getListDiem(data.Rows[i][j].ToString());
                    for (int k = 0; k < tmp.Count; k++)
                        result += (tmp[k] * lHSDiem[j - unEditCol + 1]);

                    dv += tmp.Count * lHSDiem[j - unEditCol + 1];
                }

                Boolean dungDiemHK = (Boolean)(qLTH.tbl_MonHoc.Rows[tscb_MonHoc.SelectedIndex][qLTH.tbl_MonHoc.DungDiemHocKyColumn]);
                if (!dungDiemHK)
                {
                    List<float> tmp = PublicLib.getListDiem(data.Rows[i][j].ToString());
                    for (int k = 0; k < tmp.Count; k++)
                        result += (tmp[k] * lHSDiem[j - unEditCol + 1]);

                    dv += tmp.Count * lHSDiem[j - unEditCol + 1];

                    if (dv != 0)
                        result = result / dv;
                }
                else
                {
                    if (dv != 0)
                        result = (result / dv) * 2;
                    dv = 2;
                    List<float> tmp = PublicLib.getListDiem(data.Rows[i][j].ToString());
                    for (int k = 0; k < tmp.Count; k++)
                        result += (tmp[k]);

                    dv += tmp.Count;
                    result = result / dv;
                }

                data.Rows[i][j + 1] = result.ToString(PConst.LAM_TRON); // Diem TB
            }
        }

        private void tsb_TinhDiemTB_Click(object sender, EventArgs e)
        {
            dg_DanhSach.EndEdit();
            calculateData();
        }

        private void tscb_NamHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            MyDataSet.QLTHTableAdapters.tbl_HocKyTableAdapter namAdap = new tbl_HocKyTableAdapter();
            namAdap.Connection.ConnectionString = PublicLib.getStrConn();

            idNamHoc = int.Parse(qLTH.tbl_NamHoc.Rows[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn].ToString());
            namAdap.FillByNamHoc(qLTH.tbl_HocKy, idNamHoc);

            tscb_HocKy.Items.Clear();
            for (int i = 0; i < qLTH.tbl_HocKy.Rows.Count; i++)
            {
                tscb_HocKy.Items.Add(
                    qLTH.tbl_HocKy.Rows[i][qLTH.tbl_HocKy.tenColumn].ToString());
            }

            tscb_HocKy.Items.Add(MSG.MNU_ALL_YEAR);
            if (DateTime.Now.Month > 8 || DateTime.Now.Month < 2)
                tscb_HocKy.SelectedIndex = 0; // HK I
            else
                tscb_HocKy.SelectedIndex = 1; // HK II
        }

        private void tscb_MonHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (state == PConst.STATE_LOAD)
                return;
            if (!wasSave)
            {
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
                wasSave = true;
            }
            fillData();

            if (PConst.TEST) tsb_Generate_Click(tsb_Generate, new EventArgs());
        }

        private void tsb_Generate_Click(object sender, EventArgs e)
        {
            Random rand = new Random();
            for (int i = 0; i < data.Rows.Count; i++)
            {
                for (int j = unEditCol - 1; j<data.Columns.Count - 2; j++)
                    if (data.Rows[i][j].ToString().Trim() == "")
                    {
                        data.Rows[i][j] = rand.Next(8) + 3;
                    }
            }

            calculateData();
            wasSave = false;
            saveData();
        }

        private void SoDiem_Activated(object sender, EventArgs e)
        {
            checkUserPower();
        }

        private void tsb_In_Click(object sender, EventArgs e)
        {
            PrintDataGrid.PrintDGV print = new PrintDataGrid.PrintDGV();
            print.Print_DataGridView(dg_DanhSach);
        }
    }
}
